

$(function (){
   doBrowserFix();
   preparaVariablesIniciales();
   configuraBotones()
   var oGrupos=calculaGrupos()
   window.drPropertiesPanel=new DrPropertiesPanel({containerJqSelector:"#scrollableContent", propertyGroups:oGrupos})
   drPropertiesPanel.render();
   flexify()
   bindDesktopEvents()
})

function doBrowserFix() {
   if ($.browser.mozilla)
      $("body").css({overflow:"hidden"})
}

function preparaVariablesIniciales()   {
   globalChanges={}
   skinChanges={}
}

function flexify()   {
   $('#bodyContainer').flow('vertical');
   $('html, body, #scrollableContent').flex('height', 1);
   $(document).flexify();
}

function calculaGrupos()   {
   //Tomo las variables globales
   var globalVar=drWindow.getDesktopConfig();
   var lasSkins=drWindow.getSkins()
   var skinIds=[],skinDesc=[]
   for (var i=0; i<lasSkins.length; i++) {
      skinIds[skinIds.length]=lasSkins[i].id
      if (lasSkins[i].description!=null)
         skinDesc[skinDesc.length]=lasSkins[i].description
      else
         skinDesc[skinDesc.length]=lasSkins[i].id
   }
   var globalVarMetaParam={
      globalNoClose:{description:drResources.get({bundle:"core",key:"controlPanel.txt6"}), values:"true|false", valueDescriptions:drResources.get({bundle:"core",key:"controlPanel.txt7"})}
      ,globalNoResize:{description:drResources.get({bundle:"core",key:"controlPanel.txt8"}), values:"true|false", valueDescriptions:drResources.get({bundle:"core",key:"controlPanel.txt9"})}
      ,mensajesDelSistema:{description:drResources.get({bundle:"core",key:"controlPanel.txt10"}), values:"true|false", valueDescriptions: drResources.get({bundle:"core",key:"controlPanel.txt11"}) }
      ,animacionesActivas:{description:drResources.get({bundle:"core",key:"controlPanel.txt12"}), values:"true|false", valueDescriptions: drResources.get({bundle:"core",key:"controlPanel.txt13"}) }
      ,globalNoContextMenu:{description:  drResources.get({bundle:"core",key:"controlPanel.txt14"}) , values:"true|false", valueDescriptions: drResources.get({bundle:"core",key:"controlPanel.txt15"}) }
      ,modoSinErrores:{description: drResources.get({bundle:"core",key:"controlPanel.txt16"}) , values:"true|false", valueDescriptions: drResources.get({bundle:"core",key:"controlPanel.txt17"}) }
      ,globalNoDrag:{description: drResources.get({bundle:"core",key:"controlPanel.txt18"}) , values:"true|false", valueDescriptions:drResources.get({bundle:"core",key:"controlPanel.txt19"})}
      ,margSupAnt:{noEditable:true}
      ,tema:{description: drResources.get({bundle:"core",key:"controlPanel.txt19_2"}) , values:skinIds.join("|"), valueDescriptions:skinDesc.join("|")}
      ,locale:{description: drResources.get({bundle:"core",key:"controlPanel.txt19_3"}) , values:"default|es|en", valueDescriptions: drResources.get({bundle:"core",key:"controlPanel.txt19_4"}) }      
      ,adjustWindowSizeOnOpen:{description: drResources.get({bundle:"core",key:"controlPanel.txt29"}) , values:"false|true", valueDescriptions: drResources.get({bundle:"core",key:"controlPanel.txt15"})}
   }
   //Tomo las variables particulares del skin
   var skinParameters= drWindow.getSkinParameters();
   //debugger;
   //eso son los valores pero me faltan los tipos ...
   var skinMetaParam=drWindow.getSkinMeta()
   var oRet=[]
   var grGlob={description: drResources.get({bundle:"core",key:"controlPanel.txt20"}) , fields:[], onChange:globalValueChange}
   var totalPropiedades={}
   for (a in globalVarMetaParam) 
      totalPropiedades[a]=true   
   for (a in globalVar) 
      totalPropiedades[a]=true
   for (a in totalPropiedades) {
      if (globalVarMetaParam[a]==null || !globalVarMetaParam[a].noEditable)   {
         var nuevoParam={id:a, initialValue:globalVar[a]}
         if (globalVarMetaParam[a]!=null){
            for (b in globalVarMetaParam[a])
               nuevoParam[b]=globalVarMetaParam[a][b];
         }
         grGlob.fields[grGlob.fields.length]=nuevoParam
      }
   }
   oRet[oRet.length]=grGlob;
   //Skin
   var grSkin={description: drResources.get({bundle:"core",key:"controlPanel.txt21"}) +drWindow.getSkin()+")", fields:[], onChange:skinValueChange, buttonClass:"btnRecargarValores", buttonHoverClass:"btnRecargarValoresHover", buttonOnMouseDown:btnRecargarValoresMouseDown, buttonTitle: drResources.get({bundle:"core",key:"controlPanel.txt22"})  }
   for (a in skinParameters) {
      if (skinMetaParam[a]==null ||  skinMetaParam[a].noEditable==null || skinMetaParam[a].noEditable!="true")  {
         if (a!="userBackgroundImage" || drWindow.getApplicationExists({application:"drImageSelector"}) ){
            var nuevoParam={id:a, initialValue:skinParameters[a]}
            if (skinMetaParam && skinMetaParam[a]!=null){
               if (skinMetaParam[a]!=null)  {
                  for (b in skinMetaParam[a])
                     nuevoParam[b]=skinMetaParam[a][b];
               }
            }
            grSkin.fields[grSkin.fields.length]=nuevoParam

         }
      }
   }
   oRet[oRet.length]=grSkin;
   return oRet;
}

// Eventos -----------------------------------------------------

function btnRecargarValoresMouseDown(ev){
   if (confirm( drResources.get({bundle:"core",key:"controlPanel.txt23"}) )) {
      var defaultValues=drWindow.getDesktopWindow().oDefaultSkinParameters
      //var skinParameters= drWindow.getSkinParameters();
      var fields=ev.data.objGrupo.fields
      for (var j=0; j<fields.length; j++) {
         var field=fields[j]
         var _campo=$("#p_"+field.id)
         _campo.val(""+defaultValues[field.id])
         skinChanges[field.id]={value:defaultValues[field.id]}
      }
      announce( drResources.get({bundle:"core",key:"controlPanel.txt24"}) )
   }
}

function configuraBotones()  {
   $("#cancelar").bind("click", function (){
      drWindow.close();
   }).hover(function(){$(this).addClass("hover")}, function(){$(this).removeClass("hover")})
   $("#salvar").bind("click", function (){
      consolodarCambios();
      announce( drResources.get({bundle:"core",key:"controlPanel.txt25"}) )
   }).hover(function(){$(this).addClass("hover")}, function(){$(this).removeClass("hover")})
   $("#salvarYReiniciar").bind("click", function (){
      consolodarCambios();
      //drWindow.getDesktopWindow().cerrarSesion(true)	
      drWindow.sessionSaveAndRestart()
   }).hover(function(){$(this).addClass("hover")}, function(){$(this).removeClass("hover")})
}

function globalValueChange(event)  {
   var valor= $(this).val()
   if (""+valor.toLowerCase()=="true")
      valor=true;
   else if (""+valor.toLowerCase()=="false")
      valor=false;
   var datosEv=event.data
   var id=datosEv.id
   if (id=="tema")   {
      globalChanges["temaTrasReiniciar"]={value:valor}
   } else   {
      globalChanges[id]={value:valor}
   }
   announce( drResources.get({bundle:"core",key:"controlPanel.txt26"}) )
}

function skinValueChange(event){
   var valor=$(this).val()
   var datosEv=event.data
   var id=datosEv.id
   skinChanges[id]={value:valor}
   announce( drResources.get({bundle:"core",key:"controlPanel.txt27"}) )
}

function consolodarCambios()  {
   //Repaso los cambios en el skin
   var skinParameters=drWindow.getSkinParameters();
   for (var s in skinChanges)  {
      if (skinChanges[s].value!=skinParameters[s])
         drWindow.prepareSkinParameterChange({name:s, value:skinChanges[s].value});
   }
   for (var r in globalChanges)  {
      if (r=="temaTrasReiniciar")   {
         drWindow.getDesktopWindow().temaTrasReiniciar=globalChanges[r].value;
      } else   {
         drWindow.setDesktopConfigValue({name:r, value:globalChanges[r].value})
      }
   }
}

//  obj. PANEL -----------------------------------------------------

function DrPropertiesPanel(args) {
   //Constructor
   this.settings = {containerJqSelector:"#propertiesPanel", propertyGroups:[]};
   $.extend(this.settings, args);
   this._container=$(this.settings.containerJqSelector)
   //Methods
   this.render = public_DrPropertiesPanel_render
}

function public_DrPropertiesPanel_render() {
   var html=[];
   var groups=this.settings.propertyGroups
   for (var i=0; i<groups.length; i++) {
      //var onChange=groups[i].onChange
      //var description=groups[i].description
      if (groups[i].fields!=null && groups[i].fields.length>0) {
         html[html.length]="<DIV class=\"propertyGroup\" >"
         html[html.length]="   <div class=\"propertyGroupLabel\">"+groups[i].description+"</div>"
         html[html.length]="   <div id=\"_btn_"+i+"\" class=\"btnMinimizar\"></div>"
         if (groups[i].buttonClass){
            if (groups[i].buttonTitle)
               html[html.length]="   <div id=\"_btnCustom_"+i+"\" title="+DrGeneraAtribHtml(groups[i].buttonTitle)+" class=\""+groups[i].buttonClass+"\"></div>"
            else
               html[html.length]="   <div id=\"_btnCustom_"+i+"\" class=\""+groups[i].buttonClass+"\"></div>"
         }
         html[html.length]="</DIV>"
         html[html.length]="<DIV id=\"_grupo_btn_"+i+"\" style=\"overflow:hidden;position:relative;\">"
         //html[html.length]="<DIV class=\"propertyGroup\">"+groups[i].description+"</DIV>";
         var fields=groups[i].fields
         for (var j=0; j<fields.length; j++) {   
            var field=fields[j]
            html[html.length]="<DIV class=\"propertyContainer\">"

            html[html.length]=getFieldHTML({field:field})

            if(field.description)   {
               html[html.length]="   <DIV class=\"propertyLabelContainer\" title="+DrGeneraAtribHtml(field.description)+" >"
               html[html.length]="      <div class=\"propertyLabel\">"+field.description+":</div>"
               html[html.length]="   </DIV>"
            } else {
               html[html.length]="   <DIV class=\"propertyLabelContainer\">"
               html[html.length]="      <div class=\"propertyLabel\">"+field.id+":</div>"
               html[html.length]="   </DIV>"
            }
            html[html.length]="</DIV>"
            html[html.length]="<DIV class=\"propertySeparator\"></DIV>"
         }
         html[html.length]="</DIV>"
      }
   }
   this._container.html(html.join(''))
   for (var i=0; i<groups.length; i++) {
      var grupo=groups[i]
      $("#_btn_"+i).bind("mousedown",{grupo:i},function (ev)   {
         var _btn=$(this)
         var _divGrp=$("#_grupo_btn_"+ev.data.grupo)
         if (_btn.hasClass("btnMinimizar")){
            _btn.removeClass("btnMinimizar").addClass("btnMaximizar");
            _divGrp.data("altura",_divGrp.height())
            _divGrp.animate({height:"0px"},300)
         }else{
            _btn.removeClass("btnMaximizar").addClass("btnMinimizar");
            var altura= _divGrp.data("altura")
            _divGrp.animate({height:altura+"px"},300)
         }
      }) //.hover(function(){$(this).addClass("hover")}, function(){$(this).removeClass("hover")})
      _btn=$("#_btnCustom_"+i)
      if (grupo.buttonOnMouseDown)
         _btn.bind("mousedown",{grupo:i, objGrupo: grupo},grupo.buttonOnMouseDown) //.hover(function(){$(this).addClass("hover")}, function(){$(this).removeClass("hover")})
      if (grupo.buttonHoverClass)
         _btn.hover(function(){$(this).addClass(grupo.buttonHoverClass)}, function(){$(this).removeClass(grupo.buttonHoverClass)})
      var fields=grupo.fields
      for (var j=0; j<fields.length; j++) {
         var field=fields[j]
         var _campo=$("#p_"+field.id)
         _campo.val(""+field.initialValue)
         if (grupo.onChange!=null)
            _campo.bind("change",{id:field.id},grupo.onChange)
      }
   }
}



function getFieldHTML(args)   {
   var field=args.field
   var html=[]
   if (field.values!=null) {
      html[html.length]="<DIV class=\"propertyInputContainer\" >"
      var valores=field.values.split(/\|/g)
      var valueDescriptions=[];
      if (field.valueDescriptions!=null)
         valueDescriptions=field.valueDescriptions.split(/\|/g)
      html[html.length]="<select id=\"p_"+field.id+"\" class=\"propertySelect\">";
      for (var k=0; k<valores.length; k++)
         if (valueDescriptions[k]!=null)
            html[html.length]="<option value=\""+valores[k]+"\">"+valueDescriptions[k]+"</option>";
         else
            html[html.length]="<option value=\""+valores[k]+"\">"+valores[k]+"</option>";
      html[html.length]="</select>";
      html[html.length]="</DIV>"
   }else if (field.type!=null && field.type=="imageSelect"){
      html[html.length]="         <div class=\"propertyInputWSelectorContainer\">"
      html[html.length]="            <div style=\"width:auto;height:100%;\">"
      html[html.length]="               <input id=\"p_"+field.id+"\" type=\"text\" class=\"propertyInputWSelectorText\">"
      html[html.length]="            </div>"
      html[html.length]="            <div class=\"btnFileSelect\" onmousedown=\"openSelectFileFor('p_"+field.id+"')\" onmouseover=\"$(this).addClass('btnFileSelectHover')\" onmouseout=\"$(this).removeClass('btnFileSelectHover')\"></div>"
      html[html.length]="         </div>";
   }else{
      html[html.length]="<DIV class=\"propertyInputContainer\" >"
      html[html.length]=   "<input id=\"p_"+field.id+"\" type=\"text\" class=\"propertyInputText\">"
      html[html.length]="</DIV>"
   }

   return html.join('')
}

// -----------------------------------

function announce(txt){
   $("#textLabel").html(txt)
}

function DrGeneraAtribHtml(cad) {
   if (cad==null)
      return
   return '"' + ( cad.replace(/\&/g,"&amp;").replace(/"/g,"&quot;") ) +  '"'
}

// ------------------------------------

function openSelectFileFor(inputId){
   if (! drWindow.getApplicationExists({application:"drImageSelector"})){
      drWindow.alert({message: drResources.get({bundle:"core",key:"controlPanel.txt28"}) })
      return
   }
   var windowId=drWindow.getId()
   parameters=[{name:"mode", value:"imageSelector"}, {name:"inputId", value:inputId},{name:"windowId", value:windowId}]
   drWindow.openApplication({"application":"drImageSelector", parameters:parameters})
}

function bindDesktopEvents()  {
   drEvents.bind({"type":"onDesktopFileSelect","functionName":"onDesktopFileSelect"})
}

function onDesktopFileSelect(data){
   var eventWindowId=data.windowId
   var eventInputId=data.inputId
   if (eventWindowId==drWindow.getId()){
      var file=data.file
      if (file.length>0 && (file.charAt(0)=="/" || file.charAt(0)=="\\"))
         file=file.substr(1)
      $("#"+data.inputId).val(file).trigger("change")
      drWindow.focus()
   }
}







function drEvaluaBooleanoString(valor)   {
   if (valor==null)
      return false
   if (valor==true)
      return true
   else if (valor==false)
      return false
   else  {
      var cad=(valor+"").toLowerCase()
      if (cad=="true")
         return true
      else
         return false
   }
}